package com.shengchang.hu.supervision.UI;

import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OnekeyActiviy extends BaseActivity{
    private EditText startTimeEdit,endTimeEdit;
    private TextView tv_dialog_positive,tv_dialog_negative;
    public   String str;
    OkHttpClient mOkhttp=new OkHttpClient();
    private  static  final String RUNING_URL=Contants.RUN_API;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.onekey_activiy);
        initView();
    }

    private void initView() {
        startTimeEdit=findViewById(R.id.starttime);
        startTimeEdit.setInputType(InputType.TYPE_NULL);
        startTimeEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimepiker(startTimeEdit);

            }
        });
        endTimeEdit=findViewById(R.id.endtime);
        endTimeEdit.setInputType(InputType.TYPE_NULL);
        endTimeEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTimepiker(endTimeEdit);

            }
        });
        tv_dialog_positive=findViewById(R.id.tv_dialog_positive);
        tv_dialog_positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
                runinRequest();

            }
        });
        tv_dialog_negative=findViewById(R.id.tv_dialog_negative);
        tv_dialog_negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    finish();

            }  });

    }

    private void runinRequest() {

        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCategory","0")
                .add("startDate",startTimeEdit.getText().toString())
                .add("endDate",endTimeEdit.getText().toString())
                .build();
        Request request = new Request.Builder()
                .url(RUNING_URL)
                .post(formBody)
                .build();
        Log.d("sdeujcia",RUNING_URL+"?id="+App.getApp().getToken()+"&startDate="+startTimeEdit.getText().toString()
                +"&endDate="+endTimeEdit.getText().toString()+"rubbish_category="+"0");
        Call newCall = mOkhttp.newCall(request);
        newCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {						//
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        parses(str);

                    }
                });
            }
        });

    }

    private void parses(String str) {

        try {
            JSONObject mJson=new JSONObject(str);
            String mesgJson=mJson.getString("message");
            if (mesgJson.equals("20004")){
                dismissProgressDialog();
                showShortToast("请求异常");
            }else if (mesgJson.equals("20005")){
                dismissProgressDialog();
                showShortToast("入库成功");
            }else if (mesgJson.equals("20007")){
                dismissProgressDialog();
                showShortToast("没有入库的医废");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void getTimepiker(final EditText  starttimeedit) {
        TimePickerView pvTime = new TimePickerView.Builder(OnekeyActiviy.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                String time = getTime(date2);
                starttimeedit.setText(time);
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setSubCalSize(35)
                .setContentSize(30)//滚轮文字大小
                .setTitleSize(50)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        return format.format(date);
    }
}
